package com.bh.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bh.common.annotation.DataDictClass;
import com.bh.common.constant.Entity;
import com.bh.common.core.domain.entity.SysUser;
import com.bh.common.enums.InventoryType;
import com.bh.common.enums.OrderStatus;
import com.bh.common.constant.Symbol;
import com.bh.common.exception.ServiceException;
import com.bh.common.utils.DateUtils;
import com.bh.common.utils.RedisCodeUtil;
import com.bh.common.utils.SecurityUtils;
import com.bh.common.utils.StringUtils;
import com.bh.common.utils.bean.BeanUtils;
import com.bh.common.utils.spring.SpringUtils;
import com.bh.extend.domain.*;
import com.bh.extend.mapper.JcAbnormalMapper;
import com.bh.extend.mapper.JcLedSendMapper;
import com.bh.extend.mapper.JcOrderBarcodeMapper;
import com.bh.extend.service.IJcAbnormalDetailService;
import com.bh.extend.service.IJcCustomerService;
import com.bh.ledger.domain.JcLedgerDetail;
import com.bh.ledger.mapper.JcLedgerDetailMapper;
import com.bh.order.domain.JcLed;
import com.bh.order.domain.JcLedProduct;
import com.bh.order.domain.JcLedReceivingParty;
import com.bh.order.domain.JcOrder;
import com.bh.order.dto.JcLedQueryDto;
import com.bh.order.mapper.JcLedMapper;
import com.bh.order.mapper.JcOrderMapper;
import com.bh.order.service.IJcLedProductService;
import com.bh.order.service.IJcLedReceivingpartyService;
import com.bh.order.service.IJcLedService;
import com.bh.order.service.IJcOrderTrackService;
import com.bh.order.vo.*;
import com.bh.shipment.convert.JcShipmentConvert;
import com.bh.shipment.domain.JcBerthStand;
import com.bh.shipment.domain.JcShipment;
import com.bh.shipment.domain.JcShipmentTemplate;
import com.bh.shipment.mapper.JcBerthStandMapper;
import com.bh.shipment.mapper.JcShipmentMapper;
import com.bh.shipment.service.IJcShipmentCarryService;
import com.bh.shipment.service.IJcShipmentTemplateService;
import com.bh.shipment.vo.JcAddShipmentVo;
import com.bh.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 分段订单Service业务层处理
 *
 * @author slx
 * @date 2023-04-24
 */

@Service
public class JcLedServiceImpl extends ServiceImpl<JcLedMapper, JcLed> implements IJcLedService {
    @Autowired
    private JcLedMapper jcLedMapper;
    @Autowired
    private JcOrderMapper jcOrderMapper;
    @Autowired
    private IJcOrderTrackService jcOrderTrackService;
    @Autowired
    private IJcLedReceivingpartyService jcLedReceivingpartyService;
    @Autowired
    private IJcLedProductService jcLedProductService;
    @Autowired
    private IJcCustomerService jcCustomerService;
    @Autowired
    private JcOrderBarcodeMapper jcOrderBarcodeMapper;
    @Autowired
    private JcShipmentMapper jcShipmentMapper;
    @Autowired
    private IJcShipmentTemplateService jcShipmentTemplateService;
    @Autowired
    private JcLedSendMapper jcLedSendMapper;
    @Autowired
    private JcAbnormalMapper jcAbnormalMapper;
    @Autowired
    private IJcAbnormalDetailService jcAbnormalDetailService;
    @Autowired
    private JcBerthStandMapper jcBerthStandMapper;
    @Autowired
    private JcLedgerDetailMapper ledgerDetailMapper;
    @Autowired
    private IJcShipmentCarryService shipmentCarryService;
    @Autowired
    private ISysUserService userService;
    @Resource
    private RedisCodeUtil redisCodeUtil;
    @Resource
    private JcShipmentConvert jcShipmentConvert;

    /**
     * 查询分段订单
     *
     * @param id 分段订单主键
     * @return 分段订单
     */
    @DataDictClass
    @Override
    public JcLed selectJcLedById(Long id) {
        JcLed led = jcLedMapper.selectById(id);
        if (StringUtils.isBlank(led.getCustomerName())) {
            JcCustomer customer = jcCustomerService.selectJcCustomerById(led.getJcCustomerId());
            led.setCustomerName(customer.getName());
        }
        if (StringUtils.isNotBlank(led.getQsPerson()) && StringUtils.isNumeric(led.getQsPerson())) {
            SysUser user = userService.selectUserById(Long.valueOf(led.getQsPerson()));
            if (user != null) {
                led.setQsPerson(user.getNickName());
            }
        }
        return led;
    }


    @Override
    public int signReceiving(JcLedSignReceivingVo jcLedSignReceivingVo) {
        int num = 0;
        JcOrder order;
        if (jcLedSignReceivingVo.getLedIds() != null && jcLedSignReceivingVo.getLedIds().length > 0) {
            // 批量签收
            List<JcLed> jcLeds = listByIds(Arrays.asList(jcLedSignReceivingVo.getLedIds()));
            order = jcOrderMapper.selectById(jcLeds.getFirst().getJcOrderId());
            for (JcLed led : jcLeds) {
                led.setQsTime(new Date());
                led.setQsPerson(jcLedSignReceivingVo.getUserId());
                led.setQsImgs(jcLedSignReceivingVo.getQsImgs());
                led.setStatus(OrderStatus.BACK_SEED.getValue());
                num += jcLedMapper.updateById(led);

                if (order.getIsTake() == 1) {
                    jcOrderTrackService.addTrack(order.getId(), "您的订单已被拆分:拆分单号为" + led.getCode() + "的订单已签收！", jcLedSignReceivingVo.getQsImgs());
                } else {
                    jcOrderTrackService.addTrack(order.getId(), "您的订单拆分单号为" + led.getCode() + "的订单已签收！", jcLedSignReceivingVo.getQsImgs());
                }
            }
        } else if (jcLedSignReceivingVo.getLedId() != null) {
            // 单个签收
            JcLed led = jcLedMapper.selectById(jcLedSignReceivingVo.getLedId());
            led.setQsTime(new Date());
            led.setQsPerson(jcLedSignReceivingVo.getUserId());
            led.setQsImgs(jcLedSignReceivingVo.getQsImgs());
            led.setStatus(OrderStatus.BACK_SEED.getValue());
            num = jcLedMapper.updateById(led);
            order = jcOrderMapper.selectById(led.getJcOrderId());

            if (order.getIsTake() == 1) {
                jcOrderTrackService.addTrack(order.getId(), "您的订单已被拆分:拆分单号为" + led.getCode() + "的订单已签收！", jcLedSignReceivingVo.getQsImgs());
            } else {
                jcOrderTrackService.addTrack(order.getId(), "您的订单拆分单号为" + led.getCode() + "的订单已签收！", jcLedSignReceivingVo.getQsImgs());
            }
        } else {
            throw new ServiceException("未找到对应的分段订单");
        }
        List<JcLed> leds = jcLedMapper.selectJcLedListByOrderId(order.getId());
        boolean aa = false;
        if (!leds.isEmpty()) {
            for (JcLed led1 : leds) {
                if (led1.getQsPerson() == null) {
                    order.setStatus(OrderStatus.PART_SIGN.getValue());
                    break;
                } else {
                    aa = true;
                }
            }
            if (aa) {
                order.setStatus(OrderStatus.BACK_SEED.getValue());
            }
        } else {
            throw new ServiceException("未找到对应的分段订单");
        }
        jcOrderMapper.updateById(order);
        return num;
    }

    @Override
    public int saveLedSize(JcLedSizeVo jcLedSizeVo) {
        JcLed led = selectJcLedById(jcLedSizeVo.getLedId());
        if (led.getStatus() >= OrderStatus.END_SING.getValue()) {
            throw new ServiceException("该订单已签收，不能修改件重尺");
        }
        // 计算输入值 和原值的 差异值
        int numbercz = jcLedSizeVo.getNewNumber() - jcLedSizeVo.getOldNumber();
        BigDecimal weightcz = jcLedSizeVo.getNewWeight().subtract(jcLedSizeVo.getOldWeight());
        BigDecimal volumecz = jcLedSizeVo.getNewVolume().subtract(jcLedSizeVo.getOldVolume());

        led.setNumber(jcLedSizeVo.getNewNumber());
        led.setWeight(jcLedSizeVo.getNewWeight());
        led.setVolume(jcLedSizeVo.getNewVolume());
        if (jcLedSizeVo.getNewWeight().doubleValue() >= jcLedSizeVo.getNewVolume().doubleValue() / 3) {
            led.setJzWeight(jcLedSizeVo.getNewWeight());
        } else {
            led.setJzWeight(jcLedSizeVo.getNewVolume().divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP));
        }

        List<JcLedProduct> ledProducts = jcLedProductService.selectJcLedProductListByLedId(led.getId());
        for (JcLedProduct ledProduct : ledProducts) {
            ledProduct.setNumber(jcLedSizeVo.getNewNumber());
            ledProduct.setWeight(jcLedSizeVo.getNewWeight());
            ledProduct.setVolume(jcLedSizeVo.getNewVolume());
        }
        List<JcShipment> shipments = jcShipmentMapper.selectJcShipmentListByLedId(led.getId());
        if (!shipments.isEmpty()) {
            JcShipment shipment = shipments.get(0);
            Integer shNumber = shipment.getNumber() + numbercz;
            BigDecimal spWeight = shipment.getWeight().add(weightcz);
            BigDecimal spVolume = shipment.getVolume().add(volumecz);
            if (spWeight.compareTo(spVolume.divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP)) >= 0) {
                shipment.setJzWeight(spWeight);
            } else {
                shipment.setJzWeight(spVolume.divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP));
            }
            shipment.setNumber(shNumber);
            shipment.setWeight(spWeight);
            shipment.setVolume(spVolume);
        }
        Integer number = 0;
        BigDecimal weight = BigDecimal.ZERO;
        BigDecimal volume = BigDecimal.ZERO;
        Long iddd = null;
        if (led.getJcOrderId() != null) {
            JcOrder order = jcOrderMapper.selectById(led.getJcOrderId());
            List<JcLed> leds = jcLedMapper.selectJcLedListByOrderId(led.getJcOrderId());
            for (JcLed led1 : leds) {
                weight = weight.add(led1.getWeight());
                number += led1.getNumber();
                volume = volume.add(led1.getVolume());
            }
            if (!number.equals(order.getNumber()) || !weight.equals(order.getWeight()) || !volume.equals(order.getVolume())) {
                if (weight.compareTo(volume.divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP)) > 0) {
                    order.setJzWeight(weight);
                } else {
                    order.setJzWeight(volume.divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP));
                }
                order.setNumber(number);
                order.setWeight(weight);
                order.setVolume(volume);
                order.setIsAbnormal(1);
                List<JcAbnormal> abnormals = jcAbnormalMapper.selectJcAbnormalListByOrderId(order.getId());
                List<JcAbnormalDetail> jcAbnormalDetails = new ArrayList<>();
                if (abnormals.isEmpty()) {
                    JcAbnormal abnormal = new JcAbnormal();
                    abnormal.setJcOrderId(order.getId());
                    abnormal.setJcOrganizationId(SecurityUtils.getOrgId());
                    abnormal.setType(0);
                    abnormal.setTime(new Date());
                    abnormal.setNumber(1);
                    abnormal.setDescription("修改件重尺");
                    abnormal.setCreateName(SecurityUtils.getUsername());
                    abnormal.setCreateTime(new Date());
                    jcAbnormalMapper.insert(abnormal);
                    iddd = abnormal.getId();

                    if (jcLedSizeVo.getOldNumber().intValue() != jcLedSizeVo.getNewNumber().intValue()) {
                        JcAbnormalDetail abnormalDetail = new JcAbnormalDetail();
                        abnormalDetail.setJcAbnormalId(abnormal.getId());
                        abnormalDetail.setSource("number");
                        abnormalDetail.setSourceValue(jcLedSizeVo.getOldNumber().toString());
                        abnormalDetail.setTarger("数量");
                        abnormalDetail.setTargerValue(jcLedSizeVo.getNewNumber().toString());
                        abnormalDetail.setCreateName(SecurityUtils.getUsername());
                        abnormalDetail.setCreateTime(new Date());
                        jcAbnormalDetails.add(abnormalDetail);
//                        abnormalDetailMapper.insert(abnormalDetail);
                    }
                    if (jcLedSizeVo.getOldWeight().doubleValue() != jcLedSizeVo.getNewWeight().doubleValue()) {
                        JcAbnormalDetail abnormalDetail = new JcAbnormalDetail();
                        abnormalDetail.setJcAbnormalId(abnormal.getId());
                        abnormalDetail.setSource("weight");
                        abnormalDetail.setSourceValue(jcLedSizeVo.getOldWeight().toString());
                        abnormalDetail.setTarger("重量");
                        abnormalDetail.setTargerValue(jcLedSizeVo.getNewWeight().toString());
                        abnormalDetail.setCreateName(SecurityUtils.getUsername());
                        abnormalDetail.setCreateTime(new Date());
                        jcAbnormalDetails.add(abnormalDetail);
//                        abnormalDetailMapper.insert(abnormalDetail);
                    }
                    if (jcLedSizeVo.getOldVolume().doubleValue() != jcLedSizeVo.getNewVolume().doubleValue()) {
                        JcAbnormalDetail abnormalDetail = new JcAbnormalDetail();
                        abnormalDetail.setJcAbnormalId(abnormal.getId());
                        abnormalDetail.setSource("volume");
                        abnormalDetail.setSourceValue(jcLedSizeVo.getOldVolume().toString());
                        abnormalDetail.setTarger("体积");
                        abnormalDetail.setTargerValue(jcLedSizeVo.getNewVolume().toString());
                        abnormalDetail.setCreateName(SecurityUtils.getUsername());
                        abnormalDetail.setCreateTime(new Date());
                        jcAbnormalDetails.add(abnormalDetail);
//                        abnormalDetailMapper.insert(abnormalDetail);
                    }
                } else {
                    if (jcLedSizeVo.getOldNumber().intValue() != jcLedSizeVo.getNewNumber().intValue()) {
                        JcAbnormalDetail abnormalDetail = new JcAbnormalDetail();
                        abnormalDetail.setJcAbnormalId(abnormals.get(0).getId());
                        abnormalDetail.setSource("number");
                        abnormalDetail.setSourceValue(jcLedSizeVo.getOldNumber().toString());
                        abnormalDetail.setTarger("数量");
                        abnormalDetail.setTargerValue(jcLedSizeVo.getNewNumber().toString());
                        abnormalDetail.setCreateName(SecurityUtils.getUsername());
                        abnormalDetail.setCreateTime(new Date());
                        jcAbnormalDetails.add(abnormalDetail);
//                        abnormalDetailMapper.insert(abnormalDetail);
                    }
                    if (jcLedSizeVo.getOldWeight().doubleValue() != jcLedSizeVo.getNewWeight().doubleValue()) {
                        JcAbnormalDetail abnormalDetail = new JcAbnormalDetail();
                        abnormalDetail.setJcAbnormalId(abnormals.get(0).getId());
                        abnormalDetail.setSource("weight");
                        abnormalDetail.setSourceValue(jcLedSizeVo.getOldWeight().toString());
                        abnormalDetail.setTarger("重量");
                        abnormalDetail.setTargerValue(jcLedSizeVo.getNewWeight().toString());
                        abnormalDetail.setCreateName(SecurityUtils.getUsername());
                        abnormalDetail.setCreateTime(new Date());
                        jcAbnormalDetails.add(abnormalDetail);
//                        abnormalDetailMapper.insert(abnormalDetail);

                    }
                    if (jcLedSizeVo.getOldVolume().doubleValue() != jcLedSizeVo.getNewVolume().doubleValue()) {
                        JcAbnormalDetail abnormalDetail = new JcAbnormalDetail();
                        abnormalDetail.setJcAbnormalId(abnormals.get(0).getId());
                        abnormalDetail.setSource("volume");
                        abnormalDetail.setSourceValue(jcLedSizeVo.getOldVolume().toString());
                        abnormalDetail.setTarger("体积");
                        abnormalDetail.setTargerValue(jcLedSizeVo.getNewVolume().toString());
                        abnormalDetail.setCreateName(SecurityUtils.getUsername());
                        abnormalDetail.setCreateTime(new Date());
                        jcAbnormalDetails.add(abnormalDetail);
//                        abnormalDetailMapper.insert(abnormalDetail);
                    }
                    if (!jcAbnormalDetails.isEmpty()) {
                        jcAbnormalDetailService.saveBatch(jcAbnormalDetails);
                        abnormals.get(0).setNumber(jcAbnormalDetails.size());
                        jcAbnormalMapper.updateById(abnormals.get(0));
                    }
                }
            }
        }
        return jcLedMapper.updateById(led);
    }

    /**
     * 签收功能
     *
     * @param signVo
     */
    @Override
    public int setSelfPickSign(JcLedSignReceivingVo signVo) {
        List<JcLed> signLeds = this.listByIds(Arrays.asList(signVo.getLedIds()));
        for (JcLed led : signLeds) {
            led.setId(signVo.getLedId());
            led.setQsTime(signVo.getQsTime());
            led.setQsPerson(signVo.getQsPerson());
            led.setStatus(OrderStatus.BACK_SEED.getValue());

            JcOrder order = jcOrderMapper.selectById(led.getJcOrderId());
            if (order.getIsTake() == 1) {
                jcOrderTrackService.addTrack(order.getId(), "您的订单已被拆分:拆分单号为" + led.getCode() + "的订单已签收！");
            } else {
                jcOrderTrackService.addTrack(order.getId(), "您的订单拆分单号为" + led.getCode() + "的订单已签收！");
            }
            List<JcLed> leds = jcLedMapper.selectJcLedListByOrderId(led.getJcOrderId());
            boolean aa = false;
            if (!leds.isEmpty()) {
                for (JcLed led1 : leds) {
                    if (led1.getQsPerson() == null) {
                        order.setStatus(OrderStatus.PART_SIGN.getValue());
                        break;
                    } else {
                        aa = true;
                    }
                }
                if (aa) {
                    order.setStatus(OrderStatus.BACK_SEED.getValue());
                }
            } else {
                throw new ServiceException("未找到对应的分段订单");
            }
            jcOrderMapper.updateById(order);
        }
        return SpringUtils.getBean(this.getClass()).updateBatchById(signLeds) ? 1 : 0;
    }

    @Override
    public int carryToShip(JcLedCarryToShipVo carryToShipVo) {
        //获取运单模板
        JcShipmentTemplate st = jcShipmentTemplateService.selectJcShipmentTemplateById(carryToShipVo.getTemplateId());
        //新建运单
        JcShipment shipment = jcShipmentConvert.toDO(st);
        //绑定组织机构
        shipment.setJcOrganizationId(SecurityUtils.getOrgId());
        //设置运单号
        shipment.setCode(redisCodeUtil.getShipmentCode());
        //设置运单日期
        shipment.setTime(new Date());
        //保存
        shipment.setCreateName(SecurityUtils.getUsername());
        shipment.setCreateTime(new Date());
        int num = jcShipmentMapper.insert(shipment);

        //经由站
        String orgIds = st.getOrgIds();
        if (StringUtils.isNotEmpty(orgIds)) {
            String[] orgIdArrays = orgIds.split(Symbol.COMMA);
            shipment.setBerthStand(null);
            for (int i = 0; i < orgIdArrays.length; i++) {
                JcBerthStand berthStand = new JcBerthStand();
                berthStand.setJcOrganizationId(Long.valueOf(orgIdArrays[i]));
                berthStand.setJcShipmentId(shipment.getId());
                berthStand.setJcShipmentTemplateId(null);
                berthStand.setOrderBy(i);
                berthStand.setIsArrive(0);
                berthStand.setStatus(Entity.UNACTIVE);
                berthStand.setCreateName(SecurityUtils.getUsername());
                berthStand.setCreateTime(new Date());
                jcBerthStandMapper.insert(berthStand);
            }
        }
        //获取运单模板的台账
        List<JcLedgerDetail> templateLedgers = ledgerDetailMapper.selectJcLedgerDetailListByTemplateId(st.getId());
        for (JcLedgerDetail ledgerDetail : templateLedgers) {
            ledgerDetail.setId(null);
            ledgerDetail.setJcShipmentTemplateId(null);
            ledgerDetail.setJcShipmentId(shipment.getId());
            ledgerDetail.setCreateName(SecurityUtils.getUsername());
            ledgerDetail.setCreateTime(new Date());
            ledgerDetail.setIsConfirm(0);
            ledgerDetail.setStatus(Entity.ACTIVE);
            ledgerDetailMapper.insert(ledgerDetail);
        }

        // 分段订单 配载
        JcAddShipmentVo shipmentVo = new JcAddShipmentVo();
        shipmentVo.setJcShipmentId(shipment.getId());
        shipmentVo.setLedIds(carryToShipVo.getLedIds());
        shipmentCarryService.addLed(shipmentVo);
        return num;
    }


    @DataDictClass
    @Override
    public List<JcLed> selectDeliverJcLedsByOrderId(Long jcOrderId) {
        JcLed jcLed = new JcLed();
        jcLed.setJcOrderId(jcOrderId);

        List<JcLed> leds = jcLedMapper.selectJcLedList(jcLed);
        for (JcLed led : leds) {
            if (StringUtils.isBlank(led.getCustomerName())) {
                JcCustomer customer = jcCustomerService.selectJcCustomerById(led.getJcCustomerId());
                led.setCustomerName(customer.getName());
            }
            if (StringUtils.isNotBlank(led.getQsPerson()) && StringUtils.isNumeric(led.getQsPerson())) {
                SysUser user = userService.selectUserById(Long.valueOf(led.getQsPerson()));
                if (user != null) {
                    led.setQsPerson(user.getNickName());
                }
            }
        }
        return leds;
    }

    /**
     * 外包加载货品明细
     *
     * @param jcShipmentId
     * @return
     */
    @DataDictClass
    @Override
    public List<JcLed> getWbStowageByShipmentId(Long jcShipmentId) {
        return jcLedMapper.getWbStowageByShipmentId(jcShipmentId);
    }

    @DataDictClass
    @Override
    public List<JcLed> getStowageByShipmentId(Long jcShipmentId) {
        return jcLedMapper.getStowageByShipmentId(jcShipmentId);
    }

    @Override
    public List<JcLed> getDispatchNotStowage() {
        return jcLedMapper.getDispatchNotStowage(SecurityUtils.getOrgId());
    }

    @Override
    public List<JcLed> getDispatchStowage(Long dispatchId) {
        return jcLedMapper.getDispatchStowage(dispatchId);
    }

    @Override
    public int addDispatchOrder(Long[] ledIds) {
        return jcLedMapper.addDispatchOrder(ledIds);
    }

    @DataDictClass
    @Override
    public List<JcLed> getDZLedList(Long jcShipmentId) {
        return jcLedMapper.getDZLedList(jcShipmentId);
    }


    @DataDictClass
    @Override
    public List<JcLed> selectCustomerJcLedList(JcLedQueryDto jcLedVo) {
        JcLed jcLed = new JcLed();
        jcLed.setStatus(jcLedVo.getStatus());
        jcLed.setCode(jcLedVo.getCode());
        jcLed.setJcOrderId(jcLedVo.getJcOrderId());

        List<JcLed> leds = jcLedMapper.selectJcLedList(jcLed);
        List<JcLed> newLeds = new ArrayList<>();
        if (leds != null && leds.size() > 0) {
            for (JcLed led : leds) {
                if (StringUtils.isBlank(led.getCustomerName())) {
                    JcCustomer customer = jcCustomerService.selectJcCustomerById(led.getJcCustomerId());
                    led.setCustomerName(customer.getName());
                }
                if (led.getStatus() >= OrderStatus.ARRIVE.getValue()) {
                    List<JcLedReceivingParty> ledReceivingParties = jcLedReceivingpartyService.selectJcLedReceivingPartyListByLedId(led.getId());
                    led.setLedReceivingParties(ledReceivingParties);
                    newLeds.add(led);
                }
                if (StringUtils.isNotBlank(led.getQsPerson()) && StringUtils.isNumeric(led.getQsPerson())) {
                    SysUser user = userService.selectUserById(Long.valueOf(led.getQsPerson()));
                    if (user != null) {
                        led.setQsPerson(user.getNickName());
                    }
                }
            }
        }
        return newLeds;
    }

    @Override
    public List<JcLed> selectCustomerAllJcLedList(JcLedQueryDto jcLedVo) {
        if (jcLedVo.getStatus() < 15) {
            throw new ServiceException("禁止查询此状态！");
        }
        JcLed jcLed = new JcLed();
        jcLed.setStatus(jcLedVo.getStatus());
        jcLed.setCode(jcLedVo.getCode());
        jcLed.setJcOrderId(jcLedVo.getJcOrderId());
        //设置签收人
        if (jcLedVo.getStatus() > 15) {
            jcLed.setQsPerson(SecurityUtils.getUserId().toString());
        }
        List<JcLed> leds = jcLedMapper.selectJcLedList(jcLed);
        for (JcLed led : leds) {
            if (StringUtils.isBlank(led.getCustomerName())) {
                JcCustomer customer = jcCustomerService.selectJcCustomerById(led.getJcCustomerId());
                led.setCustomerName(customer.getName());
            }
            if (StringUtils.isNotBlank(led.getQsPerson()) && StringUtils.isNumeric(led.getQsPerson())) {
                SysUser user = userService.selectUserById(Long.valueOf(led.getQsPerson()));
                if (user != null) {
                    led.setQsPerson(user.getNickName());
                }
            }
        }

        return leds;
    }

    @Override
    public List<JcLedVO> getJcLedList(JcLedVO jcLed) {
        jcLed.setJcOrganizationId(SecurityUtils.getOrgId());
        List<JcLedVO> leds = jcLedMapper.getJcLedList(jcLed);
        for (JcLedVO led : leds) {
            if (StringUtils.isNotBlank(led.getQsPerson()) && StringUtils.isNumeric(led.getQsPerson())) {
                SysUser user = userService.selectUserById(Long.valueOf(led.getQsPerson()));
                if (user != null) {
                    led.setQsPerson(user.getNickName());
                }
            }
        }
        return leds;
    }

    /**
     * 查询分段订单列表
     *
     * @param jcLed 分段订单
     * @return
     */
    @Override
    public List<JcLedVO> getOrderQS(JcLedVO jcLed) {
        jcLed.setJcOrganizationId(SecurityUtils.getOrgId());
        List<JcLedVO> leds = jcLedMapper.getOrderQS(jcLed);
        for (JcLedVO led : leds) {
            if (StringUtils.isNotBlank(led.getQsPerson()) && StringUtils.isNumeric(led.getQsPerson())) {
                SysUser user = userService.selectUserById(Long.valueOf(led.getQsPerson()));
                if (user != null) {
                    led.setQsPerson(user.getNickName());
                }
            }
        }
        return leds;
    }

    @DataDictClass
    @Override
    public List<JcLed> getLedList(Long shipmentId) {
        return jcLedMapper.selectJcLedListByShipmentId(shipmentId);
    }

    @Override
    public List<JcLedLoadingDetailVo> getLoadList(Long shipmentId) {
        // 先获取已经装载的 分段订单（LED）
        Map<String, Map<String, Long>> ledOrders = jcOrderBarcodeMapper.selectLedOrderIdsByShipmentId(shipmentId);
        // 查询已装载
        List<JcLedLoadingDetailVo> detailVos = new ArrayList<>();
        if (ledOrders.size() == 0) {
            return detailVos;
        }
        Set<String> ledOrderIds = ledOrders.keySet();
        List<JcLed> leds = this.listByIds(ledOrderIds);
        for (JcLed led : leds) {
            JcLedLoadingDetailVo detailVo = new JcLedLoadingDetailVo();
            BeanUtils.copyProperties(led, detailVo);
            List<JcLedReceivingParty> ledReceivingParties = jcLedReceivingpartyService.selectJcLedReceivingPartyListByLedId(led.getId());
            detailVo.setLedReceivingParties(ledReceivingParties);
            //补充数据
            if (ledOrders.get(led.getId()) != null) {
                detailVo.setScanNumber(ledOrders.get(led.getId()).get("scan_number").intValue());
            }
            detailVo.setNoScanNumber(detailVo.getNumber() - detailVo.getScanNumber());
            detailVo.setJcCustomerName(led.getCustomerName());
            detailVos.add(detailVo);
        }
        return detailVos;
    }

    /**
     * 目前显示了所有的应该卸载的订单
     *
     * @param shipmentId
     * @return
     */
    @Override
    public List<JcLedUnLoadingDetailVo> getUnLoadList(Long shipmentId) {
        // 先获取已经装载的 分段订单（LED）
        JcShipment shipment = jcShipmentMapper.selectById(shipmentId);
        // 因为没有提前到站，因此只能用next,正常逻辑需要用now
        List<String> ledIds = jcOrderBarcodeMapper.selectUnloadLedIdsByShipmentId(shipmentId, shipment.getJcNowOrganizationId());
        Map<String, Map<String, Long>> ledOrders = jcOrderBarcodeMapper.selectUnloadLedOrderIdsByShipmentId(shipmentId, StringUtils.join(ledIds, ","));
        // 查询已装载
        List<JcLedUnLoadingDetailVo> detailVos = new ArrayList<>();
        if (ledOrders.size() == 0) {
            return detailVos;
        }
        List<JcLed> leds = this.listByIds(ledIds);
        for (JcLed led : leds) {
            JcLedUnLoadingDetailVo detailVo = new JcLedUnLoadingDetailVo();
            BeanUtils.copyProperties(led, detailVo);
            List<JcLedReceivingParty> ledReceivingParties = jcLedReceivingpartyService.selectJcLedReceivingPartyListByLedId(led.getId());
            detailVo.setLedReceivingParties(ledReceivingParties);
            //补充数据
            if (ledOrders.get(led.getId()) != null) {
                detailVo.setScanNumber(ledOrders.get(led.getId()).get("scan_number").intValue());
            } else {
                detailVo.setScanNumber(0);
            }
            detailVo.setNoScanNumber(detailVo.getNumber() - detailVo.getScanNumber());
            detailVo.setJcCustomerName(led.getCustomerName());
            if (led.getStatus().equals(OrderStatus.DESPATCH.getValue()) || led.getStatus().equals(OrderStatus.ARRIVE.getValue())) {
                detailVo.setIsUnload(0);
            } else {
                detailVo.setIsUnload(1);
            }
            detailVos.add(detailVo);
        }
        return detailVos;
    }

    @DataDictClass
    @Override
    public List<JcLedPreSendDetailVo> getPreSendList(Long sendId) {
        // 先获取已经装载的 分段订单（LED）
        Map<String, Map<String, Long>> sendLedNum = jcOrderBarcodeMapper.selectPreSendLedOrderIdsBySendId(sendId);
        // 查询已装载
        List<JcLedPreSendDetailVo> detailVos = new ArrayList<>();
        if (sendLedNum.size() == 0) {
            return detailVos;
        }
        Set<String> ledOrderIds = sendLedNum.keySet();
        List<JcLed> leds = this.listByIds(ledOrderIds);
        for (JcLed led : leds) {
            JcLedPreSendDetailVo detailVo = new JcLedPreSendDetailVo();
            BeanUtils.copyProperties(led, detailVo);
            List<JcLedReceivingParty> ledReceivingParties = jcLedReceivingpartyService.selectJcLedReceivingPartyListByLedId(led.getId());
            for (JcLedReceivingParty ledReceivingParty : ledReceivingParties) {
                if (ledReceivingParty.getType() == 0) {
                    detailVo.setFromParties(ledReceivingParty);
                } else {
                    detailVo.setToParties(ledReceivingParty);
                }
            }
            //查询总扫码数量
            Integer scanNumber = jcOrderBarcodeMapper.countPreSendLedNumbersByLedId(led.getId());
            detailVo.setScanNumber(scanNumber);
            //补充数据
            if (sendLedNum.get(led.getId()) != null) {
                detailVo.setNowNumber(sendLedNum.get(led.getId()).get("scan_number").intValue());
            }
            detailVo.setNoScanNumber(detailVo.getNumber() - detailVo.getScanNumber());
            detailVo.setJcCustomerName(led.getCustomerName());
            detailVos.add(detailVo);
        }
        return detailVos;
    }

    @Override
    public List<JcLedVO> selectInventoryLedList(JcLedVO ledVO) {
        if (ledVO.getInventoryType() == null) {
            ledVO.setInventoryType(InventoryType.OPERATIONAL);
        }
        if (ledVO.getInventoryType() == InventoryType.OPERATIONAL) {
            //待运库
            ledVO.setStatus(OrderStatus.CONFIGRM.getValue());
        } else if (ledVO.getInventoryType() == InventoryType.SINCE) {
            //自提库
            ledVO.setStatus(OrderStatus.READY_SELF_PICK.getValue());
            ledVO.setHandoverType(0);
        } else if (ledVO.getInventoryType() == InventoryType.DISPATCHING) {
            //派送库
            ledVO.setStatus(OrderStatus.READY_SEND.getValue());
            ledVO.setHandoverType(1);
        } else if (ledVO.getInventoryType() == InventoryType.TRANSFER) {
            //中转库
            ledVO.setStatus(OrderStatus.RECEIVE.getValue());
        } else if (ledVO.getInventoryType() == InventoryType.TOMENTION) {
            //待提库
            ledVO.setStatus(OrderStatus.UNABSORBED.getValue());
        }
        return jcLedMapper.selectInventoryLedList(ledVO);
    }

    /**
     * 新增分段订单
     *
     * @param jcLed 分段订单
     * @return 结果
     */
    @Override
    public int insertJcLed(JcLed jcLed) {
        jcLed.setCreateName(SecurityUtils.getUsername());
        jcLed.setCreateTime(DateUtils.getNowDate());
        int num = jcLedMapper.insert(jcLed);
        // 新增对应地址
        if (num > 0 && jcLed.getLedReceivingParties() != null && !jcLed.getLedReceivingParties().isEmpty()) {
            for (JcLedReceivingParty ledReceivingParty : jcLed.getLedReceivingParties()) {
                ledReceivingParty.setId(null);
                ledReceivingParty.setJcLedId(jcLed.getId());
                ledReceivingParty.setCreateName(SecurityUtils.getUsername());
                ledReceivingParty.setCreateTime(DateUtils.getNowDate());
            }
            jcLedReceivingpartyService.saveBatch(jcLed.getLedReceivingParties());
        }

        // 拆分不需要新增 JcLedProduct
        if (num > 0 && jcLed.getLedProducts() != null && !jcLed.getLedProducts().isEmpty()) {
            List<JcOrderBarcode> codes = new ArrayList<>();
//            List<Long> ledProductIds = IdUtils.getManyNextId(jcLed.getLedProducts().size());
            for (int i = 0; i < jcLed.getLedProducts().size(); i++) {
                JcLedProduct ledProduct = jcLed.getLedProducts().get(i);
                Long oldProductId = ledProduct.getId();
                ledProduct.setJcLedId(jcLed.getId());
                ledProduct.setCreateName(SecurityUtils.getUsername());
                ledProduct.setCreateTime(DateUtils.getNowDate());
                // 需要置空，可能存在拆分导致ID一样的情况
                ledProduct.setId(null);
                jcLedProductService.save(ledProduct);
                // 保存二维码
                if (ledProduct.getNumber() > 0) {
                    for (int j = 0; j < ledProduct.getNumber(); j++) {
                        JcOrderBarcode orderBarcode = new JcOrderBarcode();
                        orderBarcode.setOrderId(jcLed.getJcOrderId());
                        orderBarcode.setLedOrderId(jcLed.getId());
                        orderBarcode.setProductId(oldProductId);
                        orderBarcode.setLedProductId(ledProduct.getId());
                        orderBarcode.setPackStatus("N");
                        codes.add(orderBarcode);
                    }
                }
            }
            // 保存二维码
            int coedSize = codes.size();
            if (coedSize > 0) {
                for (int i = 0; i < coedSize; i++) {
                    JcOrderBarcode code = codes.get(i);
                    code.setProductCode(jcLed.getOrderCode() + "N" + (i + 1));
                    code.setOrderBy(String.format("%04d", i + 1));
                }
            }
            jcOrderBarcodeMapper.batchInsertJcOrderBarcode(codes);
        }
        return num;
    }


    @Override
    public void handleJcLedInsert(List<JcLed> jcLeds) {
        for (JcLed jcLed : jcLeds) {
            // 新增对应地址
            if (jcLed.getLedReceivingParties() != null && jcLed.getLedReceivingParties().size() > 0) {
                for (JcLedReceivingParty ledReceivingParty : jcLed.getLedReceivingParties()) {
                    ledReceivingParty.setId(null);
                    ledReceivingParty.setJcLedId(jcLed.getId());
                    ledReceivingParty.setCreateName(SecurityUtils.getUsername());
                    ledReceivingParty.setCreateTime(DateUtils.getNowDate());
                }
                jcLedReceivingpartyService.saveBatch(jcLed.getLedReceivingParties());
            }

            // 拆分不需要新增 JcLedProduct
            if (jcLed.getLedProducts() != null && jcLed.getLedProducts().size() > 0) {
                List<JcOrderBarcode> codes = new ArrayList<>();
//                List<Long> ledProductIds = IdUtils.getManyNextId(jcLed.getLedProducts().size());
                for (int i = 0; i < jcLed.getLedProducts().size(); i++) {
                    JcLedProduct ledProduct = jcLed.getLedProducts().get(i);
                    Long oldProductId = ledProduct.getId();
                    ledProduct.setJcLedId(jcLed.getId());
                    ledProduct.setCreateName(SecurityUtils.getUsername());
                    ledProduct.setCreateTime(DateUtils.getNowDate());
                    // 需要置空，可能存在拆分导致ID一样的情况
                    ledProduct.setId(null);
                    jcLedProductService.save(ledProduct);
                    // 保存二维码
                    if (ledProduct.getNumber() > 0) {
                        for (int j = 0; j < ledProduct.getNumber(); j++) {
                            JcOrderBarcode orderBarcode = new JcOrderBarcode();
                            orderBarcode.setOrderId(jcLed.getJcOrderId());
                            orderBarcode.setLedOrderId(jcLed.getId());
                            orderBarcode.setProductId(oldProductId);
                            orderBarcode.setLedProductId(ledProduct.getId());
                            orderBarcode.setPackStatus("N");
                            codes.add(orderBarcode);
                        }
                    }
                }
                // 保存二维码
                int coedSize = codes.size();
                if (coedSize > 0) {
                    for (int i = 0; i < coedSize; i++) {
                        JcOrderBarcode code = codes.get(i);
                        code.setProductCode(jcLed.getOrderCode() + "N" + (i + 1));
                        code.setOrderBy(String.format("%04d", i + 1));
                    }
                }
                // 先删除原有的二维码
                jcOrderBarcodeMapper.deleteByOrderIds(Collections.singletonList(jcLed.getJcOrderId()));
                jcOrderBarcodeMapper.batchInsertJcOrderBarcode(codes);
            }
        }
    }

    /**
     * 修改分段订单
     *
     * @param jcLed 分段订单
     * @return 结果
     */
    @Override
    public int updateJcLed(JcLed jcLed) {
        return jcLedMapper.updateById(jcLed);
    }

    /**
     * 批量删除分段订单
     *
     * @param ids 需要删除的分段订单主键
     * @return 结果
     */
    @Override
    public int deleteJcLedByIds(Long[] ids) {
        return jcLedMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除分段订单信息
     *
     * @param id 分段订单主键
     * @return 结果
     */
    @Override
    public int deleteJcLedById(Long id) {
        return jcLedMapper.deleteById(id);
    }


    @Override
    public int confirmSend(Long sendId) {
        JcLedSend send = jcLedSendMapper.selectJcLedSendBySendId(sendId);
        send.setSendId(sendId);
        send.setSendTime(new Date());
        send.setSendStatus("Y");
        // 将设计的所有 led 设置为
        if (StringUtils.isNotBlank(send.getLedIds())) {
            List<JcLed> leds = this.listByIds(Arrays.asList(send.getLedIds().split(Symbol.COMMA)));
            if (leds != null && leds.size() > 0) {
                for (JcLed led : leds) {
                    led.setStatus(OrderStatus.READY_SEND.getValue());
                }
                SpringUtils.getBean(this.getClass()).updateBatchById(leds);
            }
        }
        return jcLedSendMapper.updateById(send);
    }
}
